import Taro, { useState, useEffect, useMemo, usePullDownRefresh } from '@tarojs/taro'
import { View } from '@tarojs/components'
import m from 'moment';

// components
import TabBar from "../../components/tabbar";
import ReportAnalysis from "../../components/reportAnalysis";
import ReportTable from "../../components/reportTable";

// utils
import getLoginInfo from "../../utils/getLoginInfo"
import getFormatSeconds from "../../utils/getFormatSeconds";

// api
import api from '../../api/index';

// style
import './index.scss'
import {REPORT_TYPE_MAP} from "../../constances/constances";

export default function History() {
  const [userData, setUserData] = useState({})
  const [current, setCurrent ] = useState(1)
  const [dailyReport, setDailyReport ] = useState([])
  const [monthlyReport, setMonthlyReport ] = useState([])
  const [todayReport, setTodayReport ] = useState([])
  const [loading, setLoading] = useState(false)

  const currentReport = {
    0: todayReport,
    1: dailyReport,
    2: monthlyReport
  }

  useEffect(async () =>{
    const user = getLoginInfo()
    setUserData(user)
    initPage(user)
  }, [])

  usePullDownRefresh(() => {
    initPage(userData).then(() => {
      Taro.stopPullDownRefresh()
    })
  })

  async function initPage(user) {
    const startToday = m().startOf('day').valueOf()
    const endToday= m().endOf('day').valueOf()
    const todayData = await api.score.getScoreDetail({
      start: startToday,
      end: endToday
    })

    if (todayData.code > 0) {
      setTodayReport(JSON.parse(todayData.data).userScoreLogList)
    }

    const start = user.user.registe_date
    const end = new Date().getTime()

    setLoading(true)

    const data = await api.score.getDayScore({
      start,
      end
    })

    if(data.code > 0) {
      setDailyReport(JSON.parse(data.data).userScoreLogList)
    }

    const monthData = await api.score.getMonthScore({
      start,
      end
    })

    setLoading(false)

    if(data.code > 0) {
      console.log('month',JSON.parse(monthData.data))
      setMonthlyReport(JSON.parse(monthData.data).userScoreLogList)
    }

  }

  function handleClickTabBar(value) {
    setCurrent(value)
  }


  function sumReportData(reportData) {
    const obj = {
      readBookCount: 0,
      recordingShareCount: 0,
      wordCount: 0,
      studySeconds: 0
    };

    reportData.map(report => {
      Object.keys(obj).map(_key => {
        obj[_key] = report[_key] + obj[_key]
      })
    })

    return obj
  }

  const todayTotalData = useMemo(() => {
    return sumReportData(todayReport)
  })

  const dailyTotalData = useMemo(() => {
    return sumReportData(dailyReport)

  }, [dailyReport])

  const monthTotalData = useMemo(() => {
    return sumReportData(monthlyReport)
  }, [monthlyReport])

  const currentTotal = {
    0: todayTotalData,
    1: dailyTotalData,
    2: monthTotalData
  }

  const currentTimeFormat = {
    1: 'YYYY-MM-DD',
    2: 'YYYY-MM'
  }

  const rows = [{
    value: currentTotal[current].readBookCount,
    label: current === 0 ? '本日阅读' : '累计阅读'
  }, {
    value: currentTotal[current].wordCount,
    label: current === 0 ? '本日单词' : '累计单词'
  }, {
    // value: (currentTotal[current].studySeconds / (60 * 60)).toFixed(1),
    value: ( current === 0 ? (currentTotal[current].studySeconds / (60)).toFixed(1) : (currentTotal[current].studySeconds / (60 *60)).toFixed(1)),
    label: current === 0 ? '本日时长(分)' : '累计时长(时)'
  }, {
    value: currentTotal[current].recordingShareCount,
    label: '录音分享'
  }]

  const tableRows = [{
    title: '日期',
    render: report => m(report.timeStamp).format(currentTimeFormat[current])
  }, {
    title: '阅读',
    // render: report => report.readBookCount
    render: report => report.readBookCount
  }, {
    title: '单词',
    render: report => report.wordCount
  }, {
    title: '录音分享',
    render: report => report.recordingShareCount
  }, {
    title: '学习时长',
    render: report => getFormatSeconds(report.studySeconds)

  },  {
    title: '',
    more: {
      onClick: (report) => {
        Taro.navigateTo({
          url: `/pages/report/index?timeStamp=${report.timeStamp}&type=${current}`
        })
      }
    }
  }]

  const todayTableRows = [{
    title: '学习时长',
    render: report => getFormatSeconds(report.studySeconds)
  }, {
    title: '单词',
    render: report => report.wordCount
  }, {
    title: '类型',
    render: report => REPORT_TYPE_MAP[report.type]
  }, {
    title: '书籍',
    maxWidth: '300rpx',
    render: report => {
      const detail = report.detailJson && JSON.parse(report.detailJson) || {}
      return detail.bookName ? `《${detail.bookName}》` : ''
    }
  }]

  const currentTableRowsMap = {
    0: todayTableRows,
    1: tableRows,
    2: tableRows,
  }

  const currentTableRows = currentTableRowsMap[current]

  return (
    <View className='history-page'>
      <View className='page-tabBar'>
        <TabBar
          values={['今日', '日汇总', '月汇总']}
          current={current}
          onClick={value => handleClickTabBar(value)}
          className='page-tabBar'
        />
      </View>

      <ReportAnalysis rows={rows} />

      <ReportTable
        dataSource={currentReport[current]}
        rows={currentTableRows}
        loading={loading}
        reportType={current}
      />
    </View>
  )
}

History.config = {
  navigationBarTitleText: '阅读记录',
  enablePullDownRefresh: true
}
